package com.xqboss.apps.service.aliyun;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.aliyun.captcha20230305.Client;
import com.aliyun.captcha20230305.models.VerifyIntelligentCaptchaRequest;
import com.aliyun.captcha20230305.models.VerifyIntelligentCaptchaResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


/**
 * 阿里云验证码服务
 *
 * @author Administrator
 */
@Service
@Slf4j
public class SampleService {
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    public Boolean check(String captchaVerifyParam, HttpServletRequest request) throws Exception {
        if (StrUtil.isBlank(captchaVerifyParam)) {
            return false;
        }
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint("captcha.cn-shanghai.aliyuncs.com");
        // 设置连接超时为5000毫秒
        config.connectTimeout = 5000;
        // 设置读超时为5000毫秒
        config.readTimeout = 5000;

        Client client = new Client(config);
        // 创建APi请求
        VerifyIntelligentCaptchaRequest req = new VerifyIntelligentCaptchaRequest();
        // 前端传来的验证参数 CaptchaVerifyParam
        req.captchaVerifyParam = captchaVerifyParam;

        try {
            VerifyIntelligentCaptchaResponse resp = client.verifyIntelligentCaptcha(req);
            log.info("阿里云验证码校验结果： {}", JSONUtil.toJsonStr(resp));
            // 获取验证码验证结果（请注意判空），将结果返回给前端。出现异常建议认为验证通过，优先保证业务可用，然后尽快排查异常原因。
            return resp.body.result.verifyResult;
//            String code = resp.body.code;
//            Boolean res = resp.body.success;
//            if (StrUtil.equals(code, "Success") && res) {
//                return true;
//            }
        } catch (TeaException error) {
            error.printStackTrace();
            log.error("阿里云验证码校验失败 ", error);
        } catch (Exception _error) {
            _error.printStackTrace();
            log.error("阿里云验证码校验失败 ", _error);
        }
        return false;
    }
}
